const dishModel = require('../../db/dish')
const respJson = require('../../utils/respJson')
const writeErr = require('../../utils/writeErr')

module.exports = {
    //获取所有商品
    async getall(req, resp) {
        try {
            let docs = await dishModel.find();
            respJson(resp, 200, '商品数据获取成功！', {
                dishes: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 505, '商品数据获取失败！')
        }
    },

    //关键字搜索
    async search(req, resp) {
        //获取传递进来的关键字
        let {
            keywords
        } = req.params
        //根据关键字获取所有商品
        try {
            let docs = await dishModel.find({
                name: new RegExp(keywords)
            })
            respJson(resp, 200, '商品数据获取成功！', {
                dishes: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 505, '商品数据获取失败！')
        }
    },

    //获取某个分类所有商品
    async catDish(req, resp) {
        let {
            catname
        } = req.params
        try {
            let docs = await dishModel.find({
                catname
            })
            respJson(resp, 200, '商品数据获取成功！', {
                dishes: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 505, '商品数据获取失败！')
        }
    },

    //根据商品ID获取商品信息
    async getOne(req, resp) {
        let {
            dishId
        } = req.params
        try {
            let docs = await dishModel.findOne({
                _id: dishId
            })
            respJson(resp, 200, '商品信息获取成功！', {
                data: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 510, '商品信息获取失败！')
        }
    }
}